<!-- 采购管理-采购任务列表 -->
<template>
  <pageHeader title="新建采购订单" :breadCrumb="breadCrumb" :show-back="true">
    <template #footer>
      <a-space>
        <a-button @click="router.back()">
          <template #default>取消</template>
        </a-button>
        <a-button type="primary" @click="handleClick">
          <template #default>提交</template>
        </a-button></a-space
      ></template
    >
    <div class="title">
      <h1>采购订单表</h1>
    </div>
    <div>
      <div class="title-item">
        <a-space style="margin-left: 40px">
          <div
            style="
              width: 5px;
              height: 23px;
              background-color: rgba(61, 126, 255, 1);
              border: none;
              border-radius: 2px;
            "
          ></div>
          <div>基本信息</div></a-space
        >
      </div>
      <div class="demand-index">
        <a-form
          ref="refForm"
          :model="demand.info"
          autoLabelWidth
          :layout="(layout as Tlayout)"
        >
          <a-row :gutter="16">
            <a-col
              v-for="item in demandForm?.info?.design?.form"
              :key="item.id"
              :span="item.span"
            >
              <FormItem
                :name="item.name"
                :componentType="item.componentType"
                v-model:props="item.props"
                :required="item.required"
                v-model:values="item.values"
                :disabled="item.disabled"
              />
            </a-col>
          </a-row>
        </a-form>
      </div>
    </div>
  </pageHeader>
  <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title> 审核信息 </template>
    <div
      ><a-form :model="demand" auto-label-width>
        <a-form-item field="priority" label="优先级">
          <a-radio-group v-model="demand.info.priority">
            <a-radio :value="4">紧急</a-radio>
            <a-radio :value="3">高</a-radio>
            <a-radio :value="2">中</a-radio>
            <a-radio :value="1">低</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form></div
    >
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import dayjs from 'dayjs';
  import { postPurchaseOrder } from '@/api/buy-management/buy-order/index';
  import { postSuppliergoods } from '@/api/buy-management/archives-details/index';
  import { getOpenTemp } from '@/api/buy-management/get-template/index';
  import { useBuyStore } from '@/store';

  const store = useBuyStore();
  const refForm = ref();
  const router = useRouter();
  const route = useRoute();
  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  const breadCrumb: string[] = ['采购管理', '采购管理', '新建采购订单'];
  const layout = ref('vertical');
  type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  interface DemandType {
    info: {
      number: string; //采购订单单号
      name: string; //采购订单名称
      description: string; //秒速
      templateId: number; //模板id
      contractId: number; //合同编号
      supplierId: number; //供应商id
      priority: number; //优先级
      state: number; //状态
      salesman: number; //业务员
      totalPrice: number; //总金额
      product: any; //订单产品
      deliveryItem: any; //交货要求
      extend: string;
      file: any;
    };
  }
  const demand = reactive<DemandType>({
    info: {
      number: '',
      name: '',
      description: '',
      templateId: 0,
      contractId: 0,
      supplierId: 0,
      priority: 0,
      state: 0,
      salesman: 0,
      totalPrice: 0,
      extend: '',
      product: [],
      deliveryItem: [],
      file: [],
    },
  });
  interface DemandFormType {
    info: {
      id: number;
      flowId: number;
      design: {
        form: any[];
      };
    };
  }
  const demandForm = reactive<DemandFormType>({
    info: { id: 0, flowId: 0, design: { form: [] } },
  });

  const orderData = ref<any>(JSON.parse(JSON.stringify(store.CreateOrder)));

  const getTemp = async () => {
    try {
      console.log(2, orderData.value);
      const res = await getOpenTemp({ type: 3 });
      demandForm.info = res;
      demandForm.info.design.form.sort((a, b) => a.sort - b.sort);
      demandForm.info.design.form.forEach((item) => {
        item.props = JSON.parse(item.props);
        if (item.values !== '') {
          item.values = JSON.parse(item.values);
          if (item.values[0] === '') {
            item.values = [];
          }
        }
        if (item.componentType === 'BUYER') {
          item.values = [userInfo.id];
        }

        if (item.componentType === 'BUY-DETAILED') {
          item.props.data = orderData.value.Product
            ? orderData.value.Product
            : [];
        }

        if (JSON.stringify(orderData.value) !== '{}') {
          if (item.componentType === 'SUOOLIER-NAME') {
            if (orderData.value.Product.length === 1)
              item.props.productId = orderData.value.Product[0].managementId;
          }
          store.CreateOrder = {};
        }
      });
    } catch (error) {
      // Handle any errors here
      console.error('Error fetching temperature:', error);
    }
  };

  getTemp();

  const visible = ref(false);
  const keys = Object.keys(demand.info);

  const handleClick = async () => {
    if (!(await refForm.value.validate())) {
      visible.value = true;
    }
  };

  const handleOk = async () => {
    visible.value = false;
    demandForm.info.design.form.forEach((item) => {
      if (item.code === 'BUY-DETAILED') {
        item.props.data.forEach((item) => {
          item.managementId = item.managementId || item.id;
          if (item.id) delete item.id;
        });
        demand.info.product = item.props.data;
      }
      if (item.code === 'FILE') {
        if (!item.props.data.length) return;
        demand.info.file = item.props.data;
        demand.info.file[0].moduleType = 4;
        delete demand.info.file[0].id;
      }
      if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
        demand.info.deliveryItem = item.props.data;
      }
      if (item.fieldName && keys.includes(item.fieldName)) {
        demand.info[item.fieldName] = item.values[0];
      }
    });
    demand.info.state = 1;
    demand.info.templateId = demandForm.info.id;
    demand.info.extend = JSON.stringify(demandForm.info.design.form);
    console.log('----00----', demand.info);
    if (demand.info.product.length) {
      demand.info.product.forEach(async (item) => {
        if (!item.supplierId) {
          await postSuppliergoods({
            singlePrice: item.guidePrice,
            singleUint: item.guidePriceUnit,
            supplierId: demand.info.supplierId,
            spec: item.spec,
            name: item.name,
            number: item.number,
            materialId: item.materialId,
            managementId: item.managementId || item.id,
            state: 1,
            isNeedAuth: 2,
            authState: 4,
          });
        }
      });
      await postPurchaseOrder(demand.info);
      router.push({
        name: 'OrderPurchaseList',
      });
    }
    store.CreateOrder = {};
  };

  const handleCancel = () => {
    visible.value = false;
  };
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .title {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }
  .demand-index {
    padding: 25px 140px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
